package com.sgb.kjwl.viewmodel.manage

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.alibaba.sdk.android.vod.upload.VODUploadCallback
import com.alibaba.sdk.android.vod.upload.VODUploadClientImpl
import com.alibaba.sdk.android.vod.upload.model.UploadFileInfo
import com.alibaba.sdk.android.vod.upload.model.VodInfo
import com.blankj.utilcode.util.RegexUtils
import com.sgb.kjwl.api.APIManager
import com.sgb.kjwl.api.service.WebsiteInfoAPI
import com.swgk.core.view.entity.AliProofEntity
import com.sgb.kjwl.model.entity.manage.AliVideoBean
import com.sgb.kjwl.model.entity.manage.PromotionalAlbumEntity
import com.sgb.kjwl.model.entity.manage.WebsiteInfoEntity
import com.swgk.core.base.BaseViewModel
import com.swgk.core.base.api.ICallBack
import com.swgk.core.base.model.entity.BaseEntity
import com.swgk.core.base.model.entity.ListResponse
import com.swgk.core.util.SharedPreferenceUtil
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import retrofit2.Call
import java.io.File

class UpLoadViewModel : BaseViewModel() {

    private var page = 1
    private val limit = 10
    val map  = HashMap<String, Any>()

    //vr列表
    val mVrList = MutableLiveData<List<PromotionalAlbumEntity>>()
    //删除的item
    val mDeletePosition = MutableLiveData<Int>()

    //删除
    val mDeleteMsg = MutableLiveData<String>()

    //图片的url
    val mPicUrl = MutableLiveData<String>()
    //图片上传成功
    val mPicUrlResult = MutableLiveData<String>()
    //视频的url
    val mVideoUrl = MutableLiveData<String>()

    //数据回显
    val mWebsiteInfoEntity = MutableLiveData<WebsiteInfoEntity>()

    //视频数据回显
    val mAliVideoBean = MutableLiveData<AliVideoBean>()

    private var mUploadClient: VODUploadClientImpl ?= null
    private var id = "" //新增 还是编辑

    fun setVideoId(id : String){
        this.id = id
    }

    fun setUploadClient(uploadClient : VODUploadClientImpl){
        this.mUploadClient = uploadClient
    }


    fun getVrList(siteNo: String, siteType: Int, isLoadMore: Boolean, type: Int) {
        page = if (isLoadMore) page + 1 else 1
        map["page"] = page
        map["limit"] = limit
        map["siteNo"] = siteNo
        map["siteType"] = siteType
        map["type"] = type
        APIManager.getInstance().websiteInfoAPI.getPromotionalAlbumList(
            WebsiteInfoAPI.WebsiteUrl.URL_ALL_SITE_ALBUM,
            map
        ).enqueue(object : ICallBack<BaseEntity<ListResponse<List<PromotionalAlbumEntity>>>>(true, true) {
            override fun onSuccess(data: BaseEntity<ListResponse<List<PromotionalAlbumEntity>>>) {
                if (data?.data != null && data.data.list != null){
                    mVrList.postValue(data.data.list)
                } else {
                    mVrList.postValue(ArrayList())
                }
            }

            override fun onFailure(
                call: Call<BaseEntity<ListResponse<List<PromotionalAlbumEntity>>>>,
                t: Throwable
            ) {
                super.onFailure(call, t)
                mVrList.postValue(ArrayList())
            }
        })
    }


    /**
     * 企业相册 删除
     */
    fun deleteVr(id: String, position : Int) {
        APIManager.getInstance().websiteInfoAPI.deleteCompanyAlbum(id).enqueue(object : ICallBack<BaseEntity<*>>(true, true) {
                override fun onSuccess(data: BaseEntity<*>) {
                    if (data.state == APIManager.RESPONSE_OK) {
                        mDeletePosition.postValue(position)
                    }
                }
            })
    }


    /**
     * 上传图片
     */
    fun uploadAvatar(file: File) {
        //创建map集合
        val photos: MutableMap<String, RequestBody> = HashMap()
        //将文件转换成多媒体文件，方便上传
        val requestBody = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file)
        photos["file" + "\"; filename=\"" + RegexUtils.getReplaceAll(
            file.name,
            "[\u4e00-\u9fa5]",
            ""
        ) + "image.jpg\""] =
            requestBody
        //接口请求
        APIManager.getInstance().uploadAPI.uploadFile(photos)
            .enqueue(object : ICallBack<BaseEntity<*>>() {
                override fun onSuccess(data: BaseEntity<*>) {
                    if (data?.data != null) {
                        mPicUrl.postValue(data.data.toString())
                    } else {
                        mPicUrl.postValue("")
                    }
                }
            })
    }

    //上传个人-企业-团队-组织logo
    fun upLoadLogo(siteNo: String, logo : String){
        val map = HashMap<String, Any>()
        map["id"] = siteNo
        map["logo"] = logo
        APIManager.getInstance().websiteInfoAPI.upLoadLogo(map).enqueue(object : ICallBack<BaseEntity<*>>(true, true){
            override fun onSuccess(data: BaseEntity<*>?) {
                if (data != null){
                    mPicUrlResult.postValue("提交成功")
                }
            }
        })
    }


    //获取视频上传凭证
    private var mProofEntity: AliProofEntity? = null
    fun getVideoParamsSTS(path: String?) {
        val map = HashMap<Any, Any>()
        APIManager.getInstance().websiteInfoAPI.getVideoParams(map).enqueue(object :
            ICallBack<BaseEntity<AliProofEntity>>() {
            override fun onSuccess(data: BaseEntity<AliProofEntity>?) {
                if (data != null && data.data != null){
                    mProofEntity = data.data
                    val vodInfo = VodInfo()
                    vodInfo.title = ""
                    vodInfo.desc = ""
                    vodInfo.cateId = System.currentTimeMillis().toInt()
                    vodInfo.tags = null
                    mUploadClient!!.addFile(path, vodInfo)
                    //阿里凭证
                    mUploadClient!!.init(mUploadCallback)
                    mUploadClient!!.start()
                }
            }

        })
    }

    //网站建设视频--详情
    fun getWebsiteVideoDetail(){
        val map = HashMap<String, Any>()
        if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1) != 0){
            map["siteNo"] = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
        } else {
            map["siteNo"] = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "")
        }
        map["siteType"] = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1)
        APIManager.getInstance().websiteInfoAPI.getWebsiteVideo(map).enqueue(object : ICallBack<BaseEntity<AliVideoBean>>(true, true){
            override fun onSuccess(data: BaseEntity<AliVideoBean>?) {
                if (data != null && data.data != null) {
                    mAliVideoBean.postValue(data.data)
                }
            }

        })
    }

    //网站建设视频--保存或者更新
    fun saveOrUpdateWebsiteVideo(id : String ="", videoId : String){
        val map = HashMap<String, Any>()
        map["id"] = id
        if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1) != 0){
            map["siteNo"] = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
        } else {
            map["siteNo"] = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "")
        }
        map["siteType"] = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1)
        map["videoId"] = videoId
        APIManager.getInstance().websiteInfoAPI.saveOrUpDateWebsiteVideo(map).enqueue(object : ICallBack<BaseEntity<*>>(true, true){
            override fun onSuccess(data: BaseEntity<*>?) {
               if (data != null){
                   message.postValue("保存成功")
               }
            }

        })
    }

    var mUploadCallback: VODUploadCallback = object : VODUploadCallback() {
        override fun onUploadSucceed(info: UploadFileInfo) {
            Log.e("onUploadSucceed", "onUploadSucceed")
            if (mProofEntity != null){
                mVideoUrl.postValue(mProofEntity!!.videoId)
            }

        }

        override fun onUploadFailed(info: UploadFileInfo, code: String, message: String) {
            Log.e("onUploadFailed", "onUploadFailed code = $code  message == $message")
        }

        override fun onUploadProgress(info: UploadFileInfo, uploadedSize: Long, totalSize: Long) {
            Log.e("onUploadFailed", "onUploadFailed")
        }

        override fun onUploadTokenExpired() {
            Log.e("onUploadTokenExpired", "onUploadTokenExpired")
            mUploadClient!!.resumeWithAuth(mProofEntity!!.uploadAuth)
        }

        override fun onUploadRetry(code: String, message: String) {
            Log.e("onUploadRetry", "onUploadRetry")
        }

        override fun onUploadRetryResume() {
            Log.e("onUploadRetryResume", "onUploadRetryResume")
        }

        override fun onUploadStarted(uploadFileInfo: UploadFileInfo) {
            Log.e("onUploadStarted", "onUploadStarted")
            mUploadClient!!.setUploadAuthAndAddress(
                uploadFileInfo,
                mProofEntity!!.uploadAuth,
                mProofEntity!!.uploadAddress
            )
        }
    }

    //-----网站logo----------------------------------------------------------------
    fun getWebsiteLogo() {
        val map = HashMap<String, Any>()
        if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1) != 0){
            map["siteNo"] = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
        } else {
            map["siteNo"] = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "")
        }
        map["siteType"] =  SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 1)
        APIManager.getInstance().websiteInfoAPI.getWebsiteLogo(map).enqueue(object : ICallBack<BaseEntity<WebsiteInfoEntity>>(true, true) {
                override fun onSuccess(data: BaseEntity<WebsiteInfoEntity>?) {
                    if (data != null && data.data != null){
                        mWebsiteInfoEntity.postValue(data.data)
                    }

                }
        })
    }

}